
import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter_ncsjqz_getx/constant/keys.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/file7_token_entity.dart';
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';

import 'toast_util.dart';

class Niu7Util {
  static Storage? _storage;
  // 工厂模式
  factory Niu7Util() =>_getInstance()!;
  static Niu7Util? get instance => _getInstance();
  static Niu7Util? _instance;
  // 创建 Controller 对象
  static PutController? putController;

  Niu7Util._internal() {
    // 初始化
    print("七牛 util");
  }

  static Niu7Util? _getInstance() {
    if (_instance == null) {
      _instance = new Niu7Util._internal();
      // 创建 storage 对象
      _storage = Storage();
      putController = PutController();
      // 添加任务状态监听
      putController!.addStatusListener((StorageStatus status) {
        print('状态变化: 当前任务状态：$status');
      });
    }
    return _instance;
  }


  /// todo：从后端获取七牛token
  static Future niu7Init() async{
    File7TokenEntity? file7tokenEntity = await DioService<File7TokenEntity>().get7AccessToken();
    if(file7tokenEntity!.code==0){
      SpUtil.putString(Keys.niu7Token, file7tokenEntity.data!.accessToken ?? '');//七牛token
      SpUtil.putString(Keys.niu7Doman, file7tokenEntity.data!.domain ?? '');//七牛访问地址
    }else{
      toast('获取七牛云token失败');
    }
  }

  Future<Null> upload(String? filePath,{Function(String)? onUrl}) async {
    await niu7Init();
    if (SpUtil.getString(Keys.niu7Token)==null) return toast('7牛云 鉴权失败 token为空');
    if (filePath == null || filePath == '') return toast('请选择文件');
    // 使用 storage 的 putFile 对象进行文件上传
    await _storage!.putFile(File(filePath), SpUtil.getString(Keys.niu7Token)!,options: PutOptions(
      controller: putController,
    ),).then((value) {
      toast("上传成功");
      print('上传已完成: url: ${SpUtil.getString(Keys.niu7Doman)!}/${value.key}');
      if(onUrl!=null)onUrl("${SpUtil.getString(Keys.niu7Doman)!}/${value.key}");
    }).catchError((error) {
      if (error is StorageError) {
        switch (error.type) {
          case StorageErrorType.CONNECT_TIMEOUT:
            print('发生错误: 连接超时');
            break;
          case StorageErrorType.SEND_TIMEOUT:
            print('发生错误: 发送数据超时');
            break;
          case StorageErrorType.RECEIVE_TIMEOUT:
            print('发生错误: 响应数据超时');
            break;
          case StorageErrorType.RESPONSE:
            if(error.code == 401){ /// token过期 更新token
              toast("上传失败，请重试！");
              niu7Init();
            }
            print('发生错误: ${error.message}');
            break;
          case StorageErrorType.CANCEL:
            print('发生错误: 请求取消');
            break;
          case StorageErrorType.UNKNOWN:
            print('发生错误: 未知错误');
            break;
          case StorageErrorType.NO_AVAILABLE_HOST:
            print('发生错误: 无可用 Host');
            break;
          case StorageErrorType.IN_PROGRESS:
            print('发生错误: 已在队列中');
            break;
        }
      } else {
        print('发生错误 err: ${error.toString()}');
      }
    });
  }
}
